<template>
  <div class="top">
    学生信息管理
    <div class="serch">
      <div class="search">
        <el-form :inline="true" :model="searchForm" class="demo-form-inline">
          <el-form-item label="学号" prop="stuid">
            <el-input v-model="searchForm.stuid" placeholder="学号"></el-input>
          </el-form-item>
          <el-form-item label="姓名" prop="stuname">
            <el-input
              v-model="searchForm.stuname"
              placeholder="姓名"
            ></el-input>
          </el-form-item>
          <el-form-item label="班级" prop="stuclass">
            <el-select v-model="searchForm.stuclass" placeholder="班级">
              <el-option label="23计1" value="23计1"></el-option>
              <el-option label="23计2" value="23计2"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="系别" class="margin" prop="studepart">
            <el-select v-model="searchForm.studepart" placeholder="系别">
              <el-option
                label="人工智能学院"
                value="人工智能学院"
              ></el-option>
              <el-option label="艺术学院" value="艺术学院"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="searchStudent">查询</el-button>
          </el-form-item>
        </el-form>
      </div>
      <el-button type="primary" @click="addStudentDialogVisible = true"
        >新增</el-button
      >
    <el-button
        type="primary"
        @click="batchDelete"
        :disabled="multipleSelection.length === 0"
      >
        批量删除
      </el-button>
    </div>
    <div>
      <el-table
        ref="multipleTable"
        :data="stuList"
        tooltip-effect="dark"
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column
          fixed
          prop="stuid"
          label="学号"
          width="80"
        ></el-table-column>
        <el-table-column
          prop="stuname"
          label="姓名"
          width="100"
        ></el-table-column>
        <el-table-column label="头像" width="80" align="center">
          <template slot-scope="scope">
            <img :src="$baseUrl + scope.row.stuavatar" width="80" />
          </template>
        </el-table-column>
        <el-table-column
          prop="stuage"
          label="年龄"
          width="100"
        ></el-table-column>
        <el-table-column
          prop="stuclass"
          label="班级"
          width="100"
        ></el-table-column>
        <el-table-column
          prop="studepart"
          label="学院"
          width="140"
        ></el-table-column>
        <!-- <el-table-column
          prop="stusex"
          label="性别"
          width="90"
        ></el-table-column> -->
        <el-table-column label="性别" width="90">
          <template slot-scope="scope">
            {{ scope.row.stusex === "0" ? "男" : "女" }}
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="100">
          <template slot-scope="scope">
            <el-button
              @click.native.prevent="deleteStudent(scope.row.stuid)"
              type="text"
              size="small"
            >
              移除
            </el-button>
            <el-button
              @click.native.prevent="editStudent(scope.row)"
              type="text"
              size="small"
              >编辑</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 新增学生对话框 -->
    <el-dialog
      title="新增学生"
      :visible.sync="addStudentDialogVisible"
      width="30%"
      @close="resetAddForm"
    >
      <el-form ref="addForm" :model="addStudentForm" label-width="80px">
        <el-form-item label="学号">
          <el-input v-model="addStudentForm.stuid"></el-input>
        </el-form-item>
        <el-form-item label="姓名">
          <el-input v-model="addStudentForm.stuname"></el-input>
        </el-form-item>
        <el-form-item label="年龄">
          <el-input v-model="addStudentForm.stuage"></el-input>
        </el-form-item>
       <el-form-item label="班级" prop="stuclass">
            <el-select v-model="addStudentForm.stuclass" placeholder="班级">
              <el-option label="23计1" value="23计1"></el-option>
              <el-option label="23计2" value="23计2"></el-option>
            </el-select>
          </el-form-item>
         <el-form-item label="系别" class="margin" prop="studepart">
            <el-select v-model="addStudentForm.studepart" placeholder="系别">
              <el-option
                label="人工智能学院"
                value="人工智能学院"
              ></el-option>
              <el-option label="艺术学院" value="艺术学院"></el-option>
            </el-select>
          </el-form-item>
        <el-form-item label="性别">
          <el-radio v-model="addStudentForm.stusex" label="0">男</el-radio>
          <el-radio v-model="addStudentForm.stusex" label="1">女</el-radio>
        </el-form-item>
        <el-form-item label="头像">
          <el-upload
            class="avatar-uploader"
            :action="$baseUrl + '/upload'"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img
              v-if="addStudentForm.stuavatar"
              :src="$baseUrl + addStudentForm.stuavatar"
              class="avatar"
            />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addStudentDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="addStudent">确定</el-button>
      </div>
    </el-dialog>
    <!-- 编辑学生对话框 -->
    <el-dialog
      title="编辑学生"
      :visible.sync="editStudentDialogVisible"
      width="30%"
      @close="resetEditForm"
    >
      <el-form ref="editForm" :model="editStudentForm" label-width="80px">
        <el-form-item label="学号">
          <el-input v-model="editStudentForm.stuid" disabled></el-input>
        </el-form-item>
        <el-form-item label="姓名">
          <el-input v-model="editStudentForm.stuname"></el-input>
        </el-form-item>
        <el-form-item label="年龄">
          <el-input v-model="editStudentForm.stuage"></el-input>
        </el-form-item>
       <el-form-item label="班级" prop="stuclass">
            <el-select v-model="editStudentForm.stuclass" placeholder="班级">
              <el-option label="23计1" value="23计1"></el-option>
              <el-option label="23计2" value="23计2"></el-option>
            </el-select>
          </el-form-item>
         <el-form-item label="系别" class="margin" prop="studepart">
            <el-select v-model="editStudentForm.studepart" placeholder="系别">
              <el-option
                label="人工智能学院"
                value="人工智能学院"
              ></el-option>
              <el-option label="艺术学院" value="艺术学院"></el-option>
            </el-select>
          </el-form-item>
        <el-form-item label="性别">
          <el-radio v-model="editStudentForm.stusex" label="0">男</el-radio>
          <el-radio v-model="editStudentForm.stusex" label="1">女</el-radio>
        </el-form-item>
        <el-form-item label="头像">
          <el-upload
            class="avatar-uploader"
            :action="$baseUrl + '/upload'"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img
              v-if="editStudentForm.stuavatar"
              :src="$baseUrl + editStudentForm.stuavatar"
              class="avatar"
            />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editStudentDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="updateStudent">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import {
  getStudents,
  deleteStudent,
  addStudent,
  updateStudent,
  findStudents,
  deleteStudentsByIds,
} from "@/api/student";

export default {
  name: "student",
  data() {
    return {
      imageUrl: "",
      searchForm: {
        // 查询条件绑定对象
        stuid: "",
        stuname: "",
        stuclass: "",
        studepart: "",
      },
      stuList: [],
      multipleSelection: [],
      addStudentDialogVisible: false,
      addStudentForm: {
        stuid: "",
        stuname: "",
        stuage: "",
        stuclass: "",
        studepart: "",
        stusex: "1",
        stuavatar: "",
      },
      editStudentDialogVisible: false,
      editStudentForm: {
        stuid: "",
        stuname: "",
        stuage: "",
        stuclass: "",
        studepart: "",
        stusex: "1",
        stuavatar: "",
      },
      formInline: {},
    };
  },
  created() {
    this.getData();
  },
  methods: {
    getData() {
      getStudents(this.searchForm).then((res) => {
        console.log("学生数据:", res.data); // 检查每条数据的 photo 字段是否有值
        this.stuList = res.data;
      });
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    //查询学生
    searchStudent() {
      findStudents(this.searchForm).then((res) => {
        if (res.code == 200) {
          this.stuList = res.data;
        } else {
          this.$message.error("查询失败");
        }
      });
    },
    //头像上传
    handleAvatarSuccess(res, file) {
      // this.imageUrl = URL.createObjectURL(file.raw);
      this.addStudentForm.stuavatar = res.data;
      console.log(this.addStudentForm.stuavatar);
       this.editStudentForm.stuavatar = res.data;
      console.log(this.editStudentForm.stuavatar);
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
    //更新
    addStudent() {
      addStudent(this.addStudentForm).then((res) => {
        if (res.data) {
          this.getData();
          this.addStudentDialogVisible = false;
          this.resetAddForm();
        }
      });
    },
    deleteStudent(stuid) {
      if (window.confirm("确定要删除该学生信息吗？")) {
        deleteStudent({ stuid }).then((res) => {
          if (res.data) {
            this.getData();
          }
        });
      }
    },
    // 实现批量删除功能
   handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    batchDelete() {
      // 如果没有选中任何学生，提示用户选择
      if (this.multipleSelection.length === 0) {
        this.$message.warning("请先选择要删除的学生！");
        return;
      }

      // 从选中的学生中提取学号（sid）
      const stuids = this.multipleSelection.map((item) => item.stuid);

      // 弹出确认对话框
      this.$confirm("此操作将永久删除所选学生，是否继续？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          // 调用后端的批量删除接口
          deleteStudentsByIds(stuids)
            .then((res) => {
              if (res.code === 200) {
                this.$message.success("批量删除成功！");
                this.getData(); // 刷新学生列表
              } else {
                this.$message.error(res.message || "批量删除失败！");
              }
            })
            .catch((err) => {
              console.error(err);
              this.$message.error("批量删除失败，请稍后重试！");
            });
        })
        .catch(() => {
          // 用户取消删除操作
          this.$message.info("已取消批量删除");
        });
    },
    editStudent(row) {
      this.editStudentDialogVisible = true;
      this.editStudentForm = { ...row };
    },
    updateStudent() {
      updateStudent(this.editStudentForm).then((res) => {
        if (res.data) {
          this.getData();
          this.editStudentDialogVisible = false;
          this.resetEditForm();
        }
      });
    },
    resetAddForm() {
      this.$refs.addForm.resetFields();
      this.addStudentForm = {
        stuid: "",
        stuname: "",
        stuage: "",
        stuclass: "",
        studepart: "",
        stusex: "",
        stuavatar: "",
      };
    },
    resetEditForm() {
      this.$refs.editForm.resetFields();
      this.editStudentForm = {
        stuid: "",
        stuname: "",
        stuage: "",
        stuclass: "",
        studepart: "",
        stusex: "",
        stuavatar: "",
      };
    },
  },
};
</script>
<style>
* {
  margin: 0px;
  padding: 0px;
}
.top {
  width: 850px;
  /* margin: 0 auto; */
}
/* 上传 */
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 100px;
  height: 100px;
  display: block;
}
</style>